#include <fcntl.h>
#include <bluetooth/bluetooth.h>
#include <sys/socket.h>
#include <bluetooth/rfcomm.h>
#include <errno.h>

int main(int argc, char *argv[])
{	
		char dest[18] = "64:A7:69:C0:75:DA";
	if( argc > 1 ){
		int sck = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

		printf("sck = %d\n", sck);
	 	sockaddr_rc loc_addr = {0}, rem_addr = {0};
	 	
	 	loc_addr.rc_family = AF_BLUETOOTH;
	 	loc_addr.rc_bdaddr = *BDADDR_ANY;
		//str2ba(dest, &loc_addr.rc_bdaddr);
	 	loc_addr.rc_channel = (uint8_t) 33;
	 	int err = bind(sck, (sockaddr *)&loc_addr, sizeof(loc_addr));	 	
	 	printf("err=%d\n", err);
	 		 	
	 	listen(sck, 1);
	 	socklen_t opt = sizeof(rem_addr);
	 	printf("listening ...\n");
	 	int client = accept(sck, (sockaddr *)&rem_addr, &opt);	 
	 	char buf[1024] = {0};
		ba2str(&rem_addr.rc_bdaddr, buf);
		printf("accepted connection from %s\n", buf);
		memset(buf, 0, sizeof(buf));
	
		int bytes_read = read(client, buf, sizeof(buf));
		if( bytes_read > 0 ){
			printf("received [%s]\n", buf);
		}
	
		close(client);
		close(sck);
	}
	else{
		sockaddr_rc addr = {0};
		int status;
		char dest[18] = "65:AA:19:B0:66:12";
		
		int sck = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
		printf("client socket=%d\n", sck);
		addr.rc_family = AF_BLUETOOTH;
		addr.rc_channel = (uint8_t)1;
		str2ba(dest, &addr.rc_bdaddr);
		status = connect(sck, (sockaddr *)&addr, sizeof(addr));
		if( status == 0 ){
			status = write(sck, "hello!", 6);
		}
		if( status < 0 ){
			printf("uh oh (%d)\n", errno);
		}
		close(sck);		
	}
	return 0;
}
